import React from 'react'
import { getUserInfo } from '@/utils/auth'

export function useHasPermission(codeOrCodes: string | string[], mode: 'any' | 'all' = 'any'): boolean {
  const userInfo = getUserInfo()
  const raw = (userInfo as { permissions?: unknown } | null)?.permissions
  const userCodes = Array.isArray(raw) ? raw.filter((v): v is string => typeof v === 'string') : []
  if (userCodes.includes('*')) return true

  const codes = Array.isArray(codeOrCodes) ? codeOrCodes : [codeOrCodes]
  if (codes.length === 0) return true

  if (mode === 'all') {
    return codes.every((c) => userCodes.includes(c))
  }
  return codes.some((c) => userCodes.includes(c))
}

type ButtonLikeProps = {
  disabled?: boolean
  [key: string]: unknown
}

type PermissionProps = {
  code: string | string[]
  mode?: 'any' | 'all'
  fallback?: React.ReactNode
  disableInstead?: boolean
  children: React.ReactElement<ButtonLikeProps>
}

export function Permission({ code, mode = 'any', fallback = null, disableInstead = false, children }: PermissionProps): React.ReactElement | null {
  const allowed = useHasPermission(code, mode)
  if (disableInstead) {
    return React.cloneElement(children, { disabled: !allowed })
  }
  if (!allowed) return (fallback as React.ReactElement) || null
  return children
}


